#include "stm32f10x.h"                  // Device header
#include <time.h>

void Rtc_settime(void);
uint16_t Rtc_time[]={2024,4,18,20,46,30};
void Rtc_Init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP,ENABLE);
	
	PWR_BackupAccessCmd(ENABLE);
	if (BKP_ReadBackupRegister(BKP_DR1)!=0x0515)
	{
		RCC_LSEConfig(RCC_LSE_ON);
		while(RCC_GetFlagStatus(RCC_FLAG_LSERDY)==RESET);
		
		RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
		RCC_RTCCLKCmd(ENABLE);
		
		RTC_WaitForSynchro();
		RTC_WaitForLastTask();
		
		RTC_SetPrescaler(32768-1);
		RTC_WaitForLastTask();
	
		Rtc_settime();
		//RTC_SetCounter(1710979200);
		RTC_WaitForLastTask();
		BKP_WriteBackupRegister(BKP_DR1,0x0515);
	}
	else
	{
		RTC_WaitForSynchro();
		RTC_WaitForLastTask();
	}
}

void Rtc_settime(void)
{
	time_t time_cnt;
	struct tm time_date;
	
	time_date.tm_year =Rtc_time[0]-1900;
	time_date.tm_mon=Rtc_time[1]-1;
	time_date.tm_mday=Rtc_time[2];
	time_date.tm_hour=Rtc_time[3];
	time_date.tm_min=Rtc_time[4];
	time_date.tm_sec=Rtc_time[5];
	
	time_cnt=mktime(&time_date)-8*60*60;
	RTC_SetCounter(time_cnt);
	RTC_WaitForLastTask();
}

void Rtc_read_time(void)
{
	time_t time_cnt;
	struct tm time_date;
	
	time_cnt=RTC_GetCounter()+8*60*60;
	
	time_date=*localtime(&time_cnt);
	Rtc_time[0]=time_date.tm_year +1900;
	Rtc_time[1]=time_date.tm_mon +1;
	Rtc_time[2]=time_date.tm_mday;
	Rtc_time[3]=time_date.tm_hour;
	Rtc_time[4]=time_date.tm_min;
	Rtc_time[5]=time_date.tm_sec;
	
}
